<template>
	<view>
		<view v-if="cartItems.length < 1 " class="uni-empty-area">
			<view class="uni-flex uni-column" style="justify-content: center; align-items: center;text-align: center;">
				<image src="../../../static/image/emptycart.png" class="empty-cart"></image>
				<view class="empty-desc">您的购物车是空的,赶紧挑选您喜爱的宝贝吧</view>
				<button class="empty-button" @click="goto">去逛逛</button>
			</view>
		</view>
		<view v-else>
			<view>
				<checkbox-group @change="checkboxChange">
					<view class="cart-list">
						<view class="cart-item" v-for="(cart, index2) in cartItems" :key="index2">
							<movable-area>
								<movable-view out-of-bounds="true" direction="horizontal" :x="cart.xmove" inertia="true" :data-productIndex="index2"
								 @bindchange="handleMovableChange">

									<view class="uni-flex uni-row " style="justify-content: center; align-items: center">
										<view class="uni-margin-10">
											<label class="checkbox" :key="index2">
												<checkbox :value="index2" :checked="cart.hasChecked">
												</checkbox>
											</label>
										</view>
										<view class="text" style="width: 160upx;height: 160upx;display: flex; justify-content: center;align-items: center;">
											<image :src="baseUrl + cart.originalImageUrl+'.tbi'" style="width: 140upx;height: 140upx;"></image>
										</view>
										<view class="uni-flex uni-column" style="flex: 1;justify-content: flex-start; padding-left: 5upx;">
											<view class="text" style="flex: 1;">{{cart.productName}}</view>
											<view class="uni-text-gray" style="flex: 1;">{{cart.productFeatureApplDesc}}</view>
											<view class="uni-flex uni-row" style="justify-content:space-between">
												<view class="uni-text-danger">￥{{cart.price}}</view>
												<view style="margin-right: 5upx;">
													<number-box :min="0" :max="1000" v-on:update="numberUpdate" :value="cart.quantity" :id="index2"></number-box>
												</view>
											</view>
										</view>

									</view>

								</movable-view>

							</movable-area>
							<view class="delete-btn" :data-productIndex="index2" @click="handleDeleteCart">删除</view>

						</view>

					</view>
				</checkbox-group>
			</view>
		</view>
		<view class="cart-bottom">
			<view class="left ">
				<checkbox-group @change="checkAllChange">
					<label class="checkbox">
						<checkbox :checked="isAllChecked"  />全选{{cartLength}}
					</label>
				</checkbox-group>
			</view>
			<view class="uni-column">
				<view class="total">总计：￥{{ sum }}</view>
			</view>

			<view class="checkout" @click="checkoutOrder" v-if="!isEditCart">确认购买</view>
		</view>



	</view>
</template>
<script>
	import numberBox from '../../../components/number-box.vue'
	import { mapState,mapMutations,mapGetters } from 'vuex'
	import {
		getUrl
	} from '@/common/oss';
	
	import { appInfo } from '@/common/appinfo'
	
	import {
		setStore
	} from '@/common/util';

	export default {
		components: {
			numberBox
		},
		data: function() {
			return {
				oldChecked: [],
				isAllChecked: false,
				baseUrl: ""
			}
		},

		onLoad: function(option) {
			uni.setNavigationBarTitle({
				title: "购物车",
			})
			if(this.hasLogin) {
				uni.showLoading({
					title:"加载中,请稍后....."
				})
				this.$store.dispatch("loadCartAction", this.userId).then(response => {
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				});
			}
			//this.getPage();
		},
		onShow: function(e){
			
			this.baseUrl = getUrl();
			
		},
		onHide: function() {
			this.pageHide = true;
		},
// 		mounted: function() {
// 		
// 			//this.$store.dispatch('loadCart');
// 		},
		computed: {
			...mapGetters(
				[ "sum", "cartLength", "hasLogin", "userId", "isCartCheckAll"]
			),
      ...mapState({
					cartItems: state => state.cart.cartItems,
        }),
    },
		mounted: function() {
			for(var i= 0; i< this.cartItems.length; i++) {
				if(this.cartItems[i].hasChecked == true) {
					this.oldChecked.push(i)
				}
			}
			if(this.cartItems.length == this.cartLength) {
				this.isAllChecked = true;
			}
		},
		methods: {
// 			 ...mapMutations(
// 				["deleteCartItem","updateCartItem"]
// 			),
			goto: function() {
				console.log("navigate to mall ....")
				uni.switchTab({
					url: '/pages/tabBar/mall/index'
				})
			},
// 			getPage() {
// 				console.log("userId:"+ this.userId);
// 
// 				if(this.hasLogin) {
// 					this.$store.dispatch("loadCartAction", this.userId)
// 				}
// 			},
			checkoutOrder: function() {
				if(!this.hasLogin) {
					uni.navigateTo({
						url:"/pages/security/login"
					})
					return;
				}
				var orderHeader = {
						orderTypeId: 'SALES_ORDER',
						statusId: 'ORDER_CREATED',
						//#ifdef APP-PLUS
						terminalId: plus.os.name,
						visitId: appInfo.deviceId,
						//#endif
						grandTotal: 0.0,
						productFeatureApplId: "",
						orderName: "",
						productFeatureDescription: "",
						orderItems: [],
						createdBy: this.userId,
						transactionMessage: "",
					}
					var i = 0;
	
					this.cartItems.forEach((item) => {
						if (item.hasChecked) {
							if (i == 0) {
								orderHeader.orderName = item.productName;
								orderHeader.productStoreId = item.productStoreId
							}
							orderHeader.orderItems.push({
								orderItemSeqId: i++,
								orderItemTypeId: 'PRODUCT_ORDER_ITEM',
								isItemGroupPrimary: "Y",
								productId: item.productId,
								productName: item.productName,
								productFeatureApplId: item.productFeatureApplId,
								productFeatureApplDesc: item.productFeatureDescription,
								originalImageUrl: item.originalImageUrl+".tbi",
								quantity: item.quantity,
								attchProps: item.attachFeatures,
								cancelQuantity: 0,
								unitListPrice: item.price,
								statusId: 'ORDER_CREATED',
								comments: this.remark
							});
							orderHeader.grandTotal = orderHeader.grandTotal + item.price * item.quantity;
						}
					})
					orderHeader.orderName = orderHeader.orderName +   "等" + orderHeader.orderItems.length + "个商品"
					setStore({
						name: '$sc_temp_order',
						content: orderHeader,
						type: 'session'
					})			
				
				uni.navigateTo({
					url: "/pages/buy/checkout?typeId=1"
				})

			},
			checkAllChange: function(e) {
				console.log("first:" + this.checkedAll)
				this.checkedAll = (!this.checkedAll);
				for (var i = 0; i < this.cartItems.length; i++) {
				
					 var select=this.cartItems[i].hasChecked;
					 if(select != this.checkedAll)
					 {
							 var cartItem = this.cartItems[i];
							 cartItem.hasChecked = this.checkedAll
							 this.$store.dispatch("updateCartAction", {
								cartItemId: cartItem,
								index:i,
								key:"hasChecked",
								value:this.checkedAll
							 })
					 }
					
				}
				console.log("second:" + this.checkedAll)
			},
			numberUpdate: function(e) {
				var id = e.id;
				var quantity=this.cartItems[id].quantity;
				var crtItem = this.cartItems[id];
				crtItem.quantity = quantity+e.val<=0?1:quantity+e.val;
				this.$store.dispatch("updateCartAction",{
						cartItem: crtItem,
					  index:i,
					  key:"quantity",
					  value:quantity+e.val<=0?1:quantity+e.val
				 })
			},
			/**
			 * 隐藏删除按钮
			 */
			hideDeleteButton: function(e) {
				let productIndex = e.currentTarget.dataset.productindex
				console.log("productIndex:" + productIndex)
				this.setXmove(productIndex, 0)
			},

			/**
			 * 设置movable-view位移
			 */
			setXmove: function(productIndex, xmove) {
				this.$store.dispatch("updateCartAction",{
					index:productIndex,
					key:"xmove",
					value:xmove
				})
			},
			/**
			 * 处理movable-view移动事件
			 */
			handleMovableChange: function(e) {
				if (e.detail.source === 'friction') {
					if (e.detail.x < -30) {
						this.showDeleteButton(e)
					} else {
						this.hideDeleteButton(e)
					}
				} else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
					this.hideDeleteButton(e)
				}
			},
			/**
			 * 显示删除按钮
			 */
			showDeleteButton: function(e) {
				let productIndex = e.currentTarget.dataset.productindex
				this.setXmove(productIndex, -65)
			},
			findPosition: function(id){
				return this.cartItems.findIndex(item=>{
					return item.cartItemId==id
				 });
			},
			checkboxChange: function(e) {
					var values = e.target.value;
					console.log(JSON.stringify(values));
					console.log("this.oldChecked:"+JSON.stringify(this.oldChecked));
					var uncheckeds = [];
					for(var i = 0; i < this.oldChecked.length; i++){
						if(values.indexOf(this.oldChecked[i]+"") < 0)
							uncheckeds.push(this.oldChecked[i]);
					}
					var newCheckeds = [];
					for(var i = 0; i < values.length; i++){
						var count = parseInt(values[i])
						if(this.oldChecked.indexOf(count) < 0)
							newCheckeds.push(count);
					}
					console.log(JSON.stringify(uncheckeds))
					for(var i= 0; i < uncheckeds.length; i++) {
						//var select=this.cartItems[uncheckeds[i]].hasChecked;
						//console.log(select);
						this.$store.dispatch("updateCartAction",{
							cartItem: this.cartItems[uncheckeds[i]],
							index:uncheckeds[i],
							key:"hasChecked",
							value:false
						}).then(response => {
							console.log("this.isAllChecked:")
							this.isAllChecked = false;
							console.log("this.isAllChecked:" +this.isAllChecked)
							this.oldChecked = values
						})
					}
					console.log("newCheckeds"+JSON.stringify(newCheckeds))
					for(var i= 0; i < newCheckeds.length; i++) {
						this.$store.dispatch("updateCartAction",{
							cartItem: this.cartItems[newCheckeds[i]],
							index:newCheckeds[i],
							key:"hasChecked",
							value:true
						}).then(response => {
							console.log("this.isAllChecked:")
							if(this.cartItems.length == this.cartLength)
								this.isAllChecked = true;
							console.log("this.isAllChecked:" +this.isAllChecked)
							this.oldChecked = values
						})
					}
					
				
				
			},

			/**
			 * 删除产品
			 */
			handleDeleteCart: function(e) {
				let productIndex = e.currentTarget.dataset.productindex
				this.$store.dispatch("deleteCartAction", {cartItemId: this.cartItems[productIndex].cartItemId, index: productIndex}).then(response => {
							if(this.cartItems.length == this.cartLength)
								this.isAllChecked = true;
								console.log("this.isAllChecked:" +this.isAllChecked)
							
						});
			},

		},


	}
</script>

<style>
	.empty-area {
		margin-top: 200upx
	}
	.empty-cart {
		width: 250upx;
		height: 250upx;
		
	}
	.empty-desc {
		margin-top: 20upx;
	}
	.empty-button {
		margin-top: 20upx;
		width: 200upx;
		height: 100upx;
		border: solid #871A8E 1px;
		border-radius: 50upx;
	}
	.cart-list .cart-item {
		position: relative;
		width: 100vw;
		border-bottom: 2upx solid #E9E9E9;
		box-sizing: border-box;
		background: #fff;
		z-index: 999;
		border-bottom: #757575 solid 1upx;
	}

	.cart-list .cart-item movable-view {
		height: 200upx;
		width: 100vw;
		background: #fff;
		z-index: 999;
	}

	.cart-list .cart-item movable-area {
		height: 200upx;
		width: calc(100vw - 120upx);
	}

	.cart-list .cart-item .delete-btn {
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		width: 120upx;
		font-size: 24upx;
		color: #FFFFFF;
		font-family: PingFangSC-Regular;
		line-height: 200upx;
		height: 200upx;
		z-index: 1;
		background: #E66671;
		text-align: center;
	}

	.cart-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 100upx;
		width: 100%;
		background: #fff;
		display: flex;
	}

	.cart-bottom .left {
		height: 34upx;
		width: auto;
		line-height: 34upx;
		margin: 28upx 10upx;
		font-size: 29upx;
		left: 0;

	}

	.cart-bottom .total {
		height: 34upx;
		flex: 1;
		margin: 33upx 10upx;
		font-size: 29upx;

	}

	.cart-bottom .checkout {
		position: absolute;
		height: 100upx;
		width: 210upx;
		text-align: center;
		line-height: 100upx;
		font-size: 29upx;
		background: #b4282d;
		right: 0;
		color: #fff;

	}
</style>
